package com.sleepfish.generator.controller.business;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement;
import com.sleepfish.common.annotation.Log;
import com.sleepfish.common.core.controller.BaseController;
import com.sleepfish.common.core.domain.AjaxResult;
import com.sleepfish.common.core.page.TableDataInfo;
import com.sleepfish.common.core.text.Convert;
import com.sleepfish.common.enums.BusinessType;
import com.sleepfish.common.utils.sql.SqlUtil;
import com.sleepfish.generator.domain.GenTable;
import com.sleepfish.generator.domain.GenTableColumn;
import com.sleepfish.generator.domain.TableColumnTran;
import com.sleepfish.generator.service.IGenDatabaseInfoService;
import com.sleepfish.generator.service.IGenTableColumnService;
import com.sleepfish.generator.service.IGenTableService;
import com.sleepfish.generator.util.BeanUtils;
import com.sleepfish.generator.util.TextTransFormUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fumingchao
 * @Description: 业务对象
 * @date 2022/2/16 19:39
 */
@Api(tags = "数据管理")
@RestController
@RequestMapping("/data/business")
public class dataManageController extends BaseController {

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenDatabaseInfoService genDatabaseInfoService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 通过表ID获取详细表信息
     */
    @ApiOperation(value = "通过表ID获取详细表信息")
    //@PreAuthorize("@ss.hasPermi('data:business:query')")
    @GetMapping(value = "/{tableId}")
    public AjaxResult getInfo(@PathVariable Long tableId)
    {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i).getColumnType().replaceAll("\\(", ",").replaceAll("\\)", "");
            String[] split = str.split(",");
            System.out.println(str);
            list.get(i).setColumnType(split[0]);
            list.get(i).setLen(split[1]);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return AjaxResult.success(map);
    }

    /**
     * 查询 表-字段 列表
     */
    @ApiOperation(value = "通过表ID查询 表-字段 列表")
    //@PreAuthorize("@ss.hasPermi('data:business:list')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @GetMapping(value = "/column/{tableId}")
    public TableDataInfo columnList(@PathVariable("tableId") Long tableId) throws Exception
    {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i).getColumnType().replaceAll("\\(", ",").replaceAll("\\)", "");
            String[] split = str.split(",");
            list.get(i).setColumnType(split[0]);
            list.get(i).setLen(split[1]);
        }
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 查找所有 数据库表 (导入)
     */
    @ApiOperation(value = "查找所有 数据库表 (导入)")
   // @PreAuthorize("@ss.hasPermi('data:business:list')")
    @GetMapping("/list")
    public TableDataInfo genList(GenTable genTable)
    {
        startPage();
        List<GenTable> list = genDatabaseInfoService.selectGenTableList(genTable);
        return getDataTable(list);
    }


    /**
     * 查找所有 数据库表 (导入)
     */
    @ApiOperation(value = "查找所有 数据库表")
    //@PreAuthorize("@ss.hasPermi('data:business:list')")
    @GetMapping("/list/pro")
    public TableDataInfo genListPro()
    {
        GenTable genTable =new GenTable();
        List<GenTable> list = genDatabaseInfoService.selectGenTableListPro(genTable);
        return getDataTable(list);
    }

    /**
     * 保存导入表数据（导入）
     */
    @ApiOperation(value = "保存导入表数据(导入)")
    //@PreAuthorize("@ss.hasPermi('data:business:import')")
    @Log(title = "业务对象", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    public AjaxResult importTableSave(String tables)
    {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genDatabaseInfoService.importGenTable(tableList,"是");
        return AjaxResult.success();
    }



    /**
     * 通过条件查找所有 数据库表 (导入)
     */
    @ApiOperation(value = "通过条件查找所有 数据库表 (导入)")
    //@PreAuthorize("@ss.hasPermi('data:business:list')")
    @GetMapping("/db/list")
    public TableDataInfo dataList(GenTable genTable)
    {
        startPage();
        List<GenTable> list = genDatabaseInfoService.selectDbTableList(genTable);
        return getDataTable(list);
    }

    @ApiOperation(value = "添加 表-字段 ")
    //@PreAuthorize("@ss.hasPermi('data:business:create')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @PostMapping("/addColTable")
    public AjaxResult addColTable(TableColumnTran tableColumnTran){
        tableColumnTran.setColumnName(tableColumnTran.getColumnName()+"_");

        String sql=tableColumnTran.addSql();
        System.out.println(tableColumnTran.getColumnType());
        try {
            genTableService.updateTable(sql);
            GenTableColumn genTableColumn=new GenTableColumn();
            tableColumnTran.setColumnType(tableColumnTran.getColumnType()+"("+tableColumnTran.getLen()+")");
            BeanUtils.copyBeanProp(genTableColumn,tableColumnTran);
//            genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName())+"_");
            genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName()));
            genTableColumnService.insertGenTableColumn(genTableColumn);
            return AjaxResult.success();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("修改表结构异常[" + e.getMessage() + "]");
        }
    }


    @ApiOperation(value = "添加 表-字段 (未生成表)")
    //@PreAuthorize("@ss.hasPermi('data:business:create')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @PostMapping("/addColTableNo")
    public AjaxResult addColTableNo(TableColumnTran tableColumnTran){

        try {
            GenTableColumn genTableColumn=new GenTableColumn();
            tableColumnTran.setColumnType(tableColumnTran.getColumnType()+"("+tableColumnTran.getLen()+")");
            BeanUtils.copyBeanProp(genTableColumn,tableColumnTran);
            genTableColumn.setColumnName(genTableColumn.getColumnName()+"_");
//            genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName())+"_");
            genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName()));
            genTableColumnService.insertGenTableColumn(genTableColumn);
            return AjaxResult.success();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("修改表结构异常[" + e.getMessage() + "]");
        }
    }

    @ApiOperation(value = "修改 表-字段 (生成后) ")
    //@PreAuthorize("@ss.hasPermi('data:business:edit')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @PutMapping("/updateColTable")
    public AjaxResult updateColTable(TableColumnTran tableColumnTran){
        if(!tableColumnTran.getColumnName().endsWith("_")){
            tableColumnTran.setColumnName(tableColumnTran.getColumnName()+"_");
        }
        System.out.println(tableColumnTran.getOldColumnName());
        String sql=tableColumnTran.updateSql();
        try {
            genTableService.updateTable(sql);
            GenTableColumn genTableColumn=new GenTableColumn();
            tableColumnTran.setColumnType(tableColumnTran.getColumnType()+"("+tableColumnTran.getLen()+")");
            BeanUtils.copyBeanProp(genTableColumn,tableColumnTran);
//            genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName())+"_");
            genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName()));
            genTableColumnService.updateGenTableColumn(genTableColumn);
            return AjaxResult.success();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("修改表结构异常[" + e.getMessage() + "]");
        }
    }

    @ApiOperation(value = "修改 表-字段 (没生成表) ")
    //@PreAuthorize("@ss.hasPermi('data:business:edit')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @PutMapping("/updateColTableNo")
    public AjaxResult updateColTableNo(TableColumnTran tableColumnTran){

        GenTableColumn genTableColumn =new GenTableColumn();
        genTableColumn.setColumnId(tableColumnTran.getColumnId());
        genTableColumn.setColumnComment(tableColumnTran.getColumnComment());
        if(!tableColumnTran.getColumnName().endsWith("_")){
            genTableColumn.setColumnName(tableColumnTran.getColumnName()+"_");
        }
        genTableColumn.setColumnType(tableColumnTran.getColumnType()+"("+tableColumnTran.getLen()+")");
//        genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName())+"_");
        genTableColumn.setJavaField(TextTransFormUtils.underlineToCamel(tableColumnTran.getColumnName()));
        genTableColumnService.updateGenTableColumn(genTableColumn);
        return AjaxResult.success();
    }

    @ApiOperation(value = "删除 表-字段 ")
    //@PreAuthorize("@ss.hasPermi('data:business:remove')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @DeleteMapping("/deleteColTable")
    public AjaxResult deleteColTable(TableColumnTran tableColumnTran){
        List<Long> ids =new ArrayList<>();
        String sql="";
        try {

            sql=tableColumnTran.deleteSql();
            genTableService.updateTable(sql);
            ids.add(tableColumnTran.getColumnId());
            genTableColumnService.deleteGenTableColumns(ids);
            return AjaxResult.success();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("修改表结构异常[" + e.getMessage() + "]");
        }
    }

    @ApiOperation(value = "删除 表-字段 ")
    //@PreAuthorize("@ss.hasPermi('data:business:remove')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @DeleteMapping("/deleteColTableNo")
    public AjaxResult deleteColTableNo(TableColumnTran tableColumnTran) {
        List<Long> ids = new ArrayList<>();

        ids.add(tableColumnTran.getColumnId());
        genTableColumnService.deleteGenTableColumns(ids);
        return AjaxResult.success();
    }

    @ApiOperation(value = "生成 表 (保存记录)")
    //@PreAuthorize("@ss.hasPermi('data:business:create')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @PostMapping("/createTable")
    public AjaxResult createTable(@RequestBody GenTable datatable)
    {
        datatable.setTableName("tb_"+datatable.getTableName());
        List<GenTable> tableList = new ArrayList<>();
        datatable.setTableName(datatable.getTableName());
        tableList.add(datatable);
        genDatabaseInfoService.importGenTable(tableList,"否");
        return AjaxResult.success();
    }


    @ApiOperation(value = "生成 表 (生成数据库表)")
    //@PreAuthorize("@ss.hasPermi('data:business:create')")
    @Log(title = "业务对象", businessType = BusinessType.GENCODE)
    @GetMapping("/sqlGenerate/{tableId}")
    public AjaxResult sqlGenerate(@PathVariable Long tableId)
    {
        GenTable datatable = genTableService.selectGenTableById(tableId);
        String sql=datatable.createSql();
        try
        {
            SqlUtil.filterKeyword(sql);
            List<SQLStatement> sqlStatements = SQLUtils.parseStatements(sql, DbType.mysql);
            List<String> tableNames = new ArrayList<>();
            for (SQLStatement sqlStatement : sqlStatements)
            {
                if (sqlStatement instanceof MySqlCreateTableStatement)
                {
                    MySqlCreateTableStatement createTableStatement = (MySqlCreateTableStatement) sqlStatement;
                    if (genTableService.createTable(createTableStatement.toString()))
                    {
                        String tableName = createTableStatement.getTableName().replaceAll("`", "");
                        tableNames.add(tableName);
                    }
                }
            }
            datatable.setGenerate("是");
            genTableService.updateGenTable(datatable);
            return AjaxResult.success();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("创建表结构异常[" + e.getMessage() + "]");
        }
    }

    /**
     * 删除代码生成
     */
    //@PreAuthorize("@ss.hasPermi('data:business:remove')")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public AjaxResult remove(@PathVariable Long[] tableIds)
    {
        genTableService.deleteGenTableByIds(tableIds);
        return AjaxResult.success();
    }

    /**
     * 同步数据库
     */
    //@PreAuthorize("@ss.hasPermi('data:business:edit')")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @GetMapping("/synchDb/{tableName}")
    public AjaxResult synchDb(@PathVariable("tableName") String tableName)
    {

        genTableService.synchDb(tableName);

        return AjaxResult.success();
    }



}
